﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MVC.OA.EFDAL
{
    public class BaseDAL<T> where T : class,new()
    {
        // DataModelContainer db = new DataModelContainer();
        //线程内共享上下文实例
        public DbContext Db { get { return DbContextFactory.GetCurrentContext(); } }
        #region 查询
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> where)
        {
            return Db.Set<T>().Where(where);
        }
        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total,
                                                 Expression<Func<T, bool>> whereLambda,
                                                   Expression<Func<T, S>> orderByLambda,
                                                    bool isAsc)
        {
            total = Db.Set<T>().Where(whereLambda).Count();

            if (isAsc)
            {
                var temp = Db.Set<T>().Where(whereLambda)
                             .OrderBy<T, S>(orderByLambda)
                             .Skip(pageSize * (pageIndex - 1))
                             .Take(pageSize).AsQueryable();

                return temp;
            }
            else
            {
                var temp = Db.Set<T>().Where(whereLambda)
                               .OrderByDescending<T, S>(orderByLambda)
                               .Skip(pageSize * (pageIndex - 1))
                               .Take(pageSize).AsQueryable();

                return temp;

            }
        }
        #endregion

        #region cud
        public bool Add(T Entity)
        {
            Db.Set<T>().Add(Entity);
            return true;
        }

        public bool Update(T Entity)
        {
            Db.Entry(Entity).State = EntityState.Modified;
            return true;
        }


        public bool Delete(T Entity)
        {
            Db.Entry(Entity).State = EntityState.Deleted;
            return true;
        }
        #endregion
    }

}
